<?php

/**
 * Class for handling information used to generate visual pager for paging database data
 *
 * @magic int getCurrentPage() Returns current page number
 * @magic int getPageCount() Returns number of pages
 * @magic void setPageCount(int $count) Sets number of pages
 */
abstract class Pager
{
	/**
	 * Number of pages
	 *
	 * @var int
	 */
	protected $pageCount;
	/**
	 * Current page number
	 *
	 * @var int
	 */
	protected $currentPage = 1;

	/**
	 * Constructs pager object
	 *
	 * @param int $totalPages
	 */
	public function __construct($totalPages)
	{
		$this->pageCount = $totalPages;
	}

	/**
	 * Returns number of pages
	 *
	 * @return int
	 */
	public function getPageCount()
	{
		return $this->pageCount;
	}

	/**
	 * Checks whether there is page previous to the current
	 *
	 * @return bool
	 */
	public function hasPrevPage()
	{
		return (bool)($this->currentPage > 1);
	}

	/**
	 * Checks whether there are more pages
	 *
	 * @return bool
	 */
	public function hasNextPage()
	{
		return (bool)($this->currentPage < $this->pageCount);
	}

	/**
	 * Returns current page
	 *
	 * @return int
	 */
	public function getCurrentPage()
	{
		return $this->currentPage;
	}

	/**
	 * Sets current page
	 *
	 * @param int $pageNo
	 */
	public function setCurrentPage($pageNo)
	{
		if ($pageNo < 1 || $pageNo > $this->pageCount)
			throw new Exception('Invalid page number - out of bounds');

		$this->currentPage = $pageNo;
	}

	/**
	 * Returns array of page numbers used for generation of visual page selector list
	 *
	 * Note: the actual length of selector list may be shorter than selectorLength if pageCount is smaller
	 * @param int $selectorLength nominal number of elements on selector list
	 * @return array
	 */
	public function getPageSelector($selectorLength)
	{
		if ($selectorLength > $this->pageCount || $selectorLength < 1)
			$selectorLength = $this->pageCount;

		$leftWndPos = floor((2 * $this->currentPage - $selectorLength + 1) / 2);

		if ($leftWndPos < 1)
			$leftWndPos = 1;
		$rightWndPos = $leftWndPos + $selectorLength - 1;

		if ($rightWndPos > $this->pageCount)
		{
			$rightWndPos = $this->pageCount;
			$leftWndPos = $rightWndPos - $selectorLength + 1;
		}

		return range($leftWndPos, $rightWndPos);
	}
}
?>